package com.nbsaas.boot.websocket;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.nbsaas.boot.rest.response.ResponseObject;
import com.nbsaas.boot.security.config.MySessionManager;
import com.nbsaas.boot.user.ext.domain.response.UserInfoExtResponse;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.springframework.beans.BeanUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

public class TalkSocketHandler extends TextWebSocketHandler {

    public List<WebSocketSession> sessions = new ArrayList<>();

    public Map<String, WebSocketSession> sessionMap = new Hashtable<>();


    @Resource
    private MySessionManager mySessionManager;


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 处理来自客户端的消息
        String payload = message.getPayload();
        System.out.println(sessionMap.size());
        JSONObject obj = null;
        try {
            obj = JSON.parseObject(payload);
        } catch (Exception e) {
            session.sendMessage(new TextMessage(JSON.toJSONString(ResponseObject.error(501, "无效数据格式"))));
            return;
        }

        String sessionId = obj.getString("sessionId");
        if (sessionId == null) {
            session.sendMessage(new TextMessage(JSON.toJSONString(ResponseObject.error(501, "没有会话id"))));
            return;
        }
        try {
            UserInfoExtResponse result = getUserInfoExtResponse(sessionId);
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
            session.sendMessage(new TextMessage(JSON.toJSONString(ResponseObject.error(401, "会话失效"))));
        }


        // 这里可以编写处理消息的逻辑
    }

    private UserInfoExtResponse getUserInfoExtResponse(String sessionId) {
        Session temp = mySessionManager.getSession(new DefaultSessionKey(sessionId));
        Object user = temp.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (user == null) {
            return null;
        }
        if (user instanceof SimplePrincipalCollection) {
            SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) user;
            Object obj = simplePrincipalCollection.getPrimaryPrincipal();

            if (obj instanceof UserInfoExtResponse) {
                return (UserInfoExtResponse) obj;
            }
            UserInfoExtResponse result = new UserInfoExtResponse();
            BeanUtils.copyProperties(obj, result);
            return result;
        }

        if (user instanceof UserInfoExtResponse) {
            return (UserInfoExtResponse) user;
        }
        UserInfoExtResponse result = new UserInfoExtResponse();
        BeanUtils.copyProperties(user, result);
        return result;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 当WebSocket连接建立时调用
        super.afterConnectionEstablished(session);

        // 添加新连接的WebSocketSession到集合中
        sessions.add(session);
        sessionMap.put(session.getId(), session);
        // 执行其他初始化操作...
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 当WebSocket连接关闭时调用
        sessions.remove(session);
        sessionMap.remove(session.getId());

    }
}
